package org.summerframework.core.util;

import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

public class CheckUtil extends StringUtils {

    private final static Map<String, Pattern> PATTERN_MAP = new HashMap<>();

    public final static String EMAIL = "^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$";

    public final static String MOBILE = "^1[3|4|5|7|8|9][0-9]\\d{8}$";

    public final static String REGEX_PHONE = "^((\\d{3,4}([\\- ]?))?)\\d{3,8}((\\-\\d{1,6})?)$";

    public final static String NUMBER = "^[0-9]*[1-9][0-9]*$";

    public final static String FLOAT_NUMBER = "^\\d+(\\.\\d+)?$";

    public final static String URL = "^(?:((ht|f)tps?)://)?(?:(www.)?+[A-Za-z0-9\\.-]+\\.[A-Za-z]{2,3}|\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})(:\\d{1,5})?(?:/[a-zA-Z0-9-\\._\\?,'\\+&%\\$=~\\*!:@#\\\\]*)*$";

    public final static String START_LIKE_URL = "((http|https|ftp)://)(.+)";

    public final static String IDENTITY_CARD = "^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$|^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9]|X|x)$";

    public static boolean isEmail(String email) {
        return checkReg(EMAIL, email);
    }

    public static boolean isMobile(String mobile) {
        return checkReg(MOBILE, mobile);
    }

    public static boolean isPhone(String phone) {
        return checkReg(REGEX_PHONE, phone);
    }

    public static boolean isNumber(String number) {
        return checkReg(NUMBER, number);
    }

    public static boolean isFloat(String number) {
        return checkReg(FLOAT_NUMBER, number);
    }

    public static boolean isUrl(String number) {
        return checkReg(URL, number);
    }

    public static boolean isIdentityCard(String identityCard) { return checkReg(IDENTITY_CARD, identityCard); }

    /**
     * 判断url是否以http://、https://或ftp://开头
     *
     * @param url
     */
    public static boolean isUrlCheckStart(String url) {
        return checkReg(START_LIKE_URL, url);
    }

    public static boolean checkReg(String reg, CharSequence obj) {
        return obj != null && reg != null && PATTERN_MAP.computeIfAbsent(reg, Pattern::compile).matcher(obj).matches();
    }

    public static void main(String[] args) {
        System.out.println(isMobile("18979830321"));
    }
}
